package cn.tedu.charging.order.service.impl;

import cn.tedu.charging.common.pojo.param.OrderAddParam;
import cn.tedu.charging.common.protocol.JsonResult;
import cn.tedu.charging.common.utils.SnowflakeIdGenerator;
import cn.tedu.charging.order.client.DeviceClient;
import cn.tedu.charging.order.client.UserClient;
import cn.tedu.charging.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private DeviceClient deviceClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private SnowflakeIdGenerator idGenerator;
    @Override
    public String createOrder(OrderAddParam param) {
        //1.检查设备--轻做 第一次使用openFeign复习
        checkGunAvailabe(param.getGunId());
        //2.检查车主--轻做
        checkUserVehicleAvailable(param.getUserId(),param.getGunId());
        //3.订单编号生成--雪花算法
        String billId=generateBillId();
        //TODO 4.和设备通信 发送开始充电命令--emqx异步消息
        //sendStartCharging();
        //TODO 5.发送延迟消息 对自检结果做补充操作--rabbitmq延迟逻辑
        //sendDelayCheck();
        //TODO 6.为兜底检查订单最终状态 发布长时间延迟定时任务--xxl-job客户端
        //createBillTask();
        //TODO 7.修改枪状态为 使用中
        //updateGunUsing();
        return billId;
    }

    private String generateBillId() {
        return idGenerator.nextId()+"";
    }

    private void checkUserVehicleAvailable(Integer userId, Integer gunId) {
        JsonResult<Boolean> result = userClient.checkUserCharge(userId, gunId);
        Boolean available = result.getData();
        if (!available) {
            throw new RuntimeException("车主或者车辆与当前充电设备不匹配");
        }
    }

    private void checkGunAvailabe(Integer gunId) {
        //调用发起
        JsonResult<Boolean> result = deviceClient.checkGun(gunId);
        Boolean available = result.getData();
        //判断返回值是否可用
        if (!available) {
            throw new RuntimeException("枪状态异常,不可充电");
        }
    }
}
